# If running on devices without essential libraries, uncomment the next line:
# !pip install -U poly2graph sympy networkx matplotlib
import sympy as sp
import numpy as np
np.set_printoptions(threshold=20)
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import networkx as nx
# Poly2Graph (must be installed in your environment)
# If this import fails, run the pip command above.
import poly2graph as p2gSpectral Graphs & Poly2Graph — A Hands‑On Tutorial
1 Introduction
This tutorial is for the ones don’t have physics background, introducing the concepts of spectral graphs and demonstrates how to use the Poly2Graph library to create and manipulate spectral graphs in Python.
To fully benefit from this tutorial, you should have a basic understanding of Python programming and mathematical background on linear algebra and complex functions.
2 Learning objectives
By the end of this tutorial, you will be able to:
- Explain what a spectral graph is (a graph traced by the energy spectrum of a 1‑D crystal on the complex plane under open boundaries).
- Understand the key mathematical objects that appear in modern treatments: the characteristic polynomial \(P(z,E)\), the spectral potential \(\Phi(E)\), and the density of states \(\rho(E)\).
- Describe prior pain points (manual inspection, numerical bottlenecks, fragile extraction) and the need for an automated tool.
- Use
Poly2Graphto go from a symbolic Hamiltonian/characteristic polynomial to its spectral graph, and analyze/visualize the result.
Figure 1. Concept map
The Figure 1 shows the concept map of this tutorial, (a) starting from 1-D crystal Hamiltonian \(H(z)\) in momentum space, or its characteristic polynomial \(P(z,E) = z^2 + 1/z^2 + 10Ez - E^4\), (b) calculating the spectral potential \(\Phi(E)\) (Rokin Function) through the roots of \(P(z,E) = 0\), (c) the density of states \(\rho(E)\), obtained as the Laplacian of \(\Phi(E)\) and (d) visualizing the spectral graph through sg.spectral_graph() based on NetWorkX.
3 What is a spectral graph?
Consider a simple 1‑D crystal (a line of repeating “cells” in Figure 1(a)), electrons in a cell are possible hopping to neighbor cells (the “arrow” terms in Figure 1(a)). It is a classic scenario in non-Hermitian system. A good visualized way to uncover the system’s energy structure is to plot a spectral graph. What actually is a spectral graph? Here is a specific explanation.
To seize the concept accurately, we start from a linear algebra viewpoint: studying a family of matrices built on local hoppings (couplings) between neighboring cells.
Non-Hermitian simply means the matrix \(H\) is not equal to its conjugate transpose \(H^\dagger\). This can happen if forward and backward hoppings differ or if we have gain/loss factors (e.g. non-reciprocal hoppings or some sort of on-site potentials). Consequently its eigenvalues need not be real, they live in \(\mathbb{C}\).
Two boundary conditions cause two global matrix structures:
- Periodic Boundary Conditions (PBC): allowing hoppings between boundaries, the matrix “wraps around” (i.e., the first and last cells are coupled) — it is (block) circulant.
- Open Boundary Conditions (OBC): turning off boundary hoppings, the wrap is cut — the matrix is (block) banded Toeplitz.
- Periodic Boundary Conditions (PBC): allowing hoppings between boundaries, the matrix “wraps around” (i.e., the first and last cells are coupled) — it is (block) circulant.
Under PBC (circulant case) eigenvalues are easy to understand: a circulant (or block circulant) matrix is diagonalized by Discrete Fourier Transform (DFT) from real space to momentum space. Writing a small “Bloch” matrix \(h(z)\) with \(z=e^{ik}\), sampling \(k\in[0,2\pi)\) makes the eigenvalues trace smooth closed curves or loops in the complex plane.
Under OBC (Toeplitz case) the same local rules yield a different global matrix. In the thermodynamic limit (number of cells \(N\to\infty\)), the OBC spectrum generally does not fill those PBC loops. Instead, it is supported on thin curves (arcs and sometimes closed loops) in the complex \(E\)‑plane. Connecting these curves yields a planar network: the spectral graph.
In conclusion: a spectral graph is the OBC spectrum in the thermodynamic limit (\(N\to\infty\)) viewed as a network of curves in the complex \(E\)‑plane.
For more mathematical details, see Section 7.
4 Why interesting?
Now we have a basic understanding of what a spectral graph is. However, which domains can benefit from spectral graphs? Why are spectral graphs interesting? Here are some views:
Within Non‑Hermitian systems:
Non-Hermitian spectra can realize a plethora of graph connectivities than standard topological labels (like \(\mathbb{Z},\mathbb{Z}_2\)): stars, flowers, braids, etc., with novel transitions that change the number of endpoints/junctions/loops (no Hermitian analog). This is naturally expressed by writing dispersions as bivariate Laurent polynomials \(P(E,z)\) and studying how their imaginary‑momentum (“inverse skin depth” \(\log|z|\)) surfaces intersect across the \(E\)‑plane.
Beyond Non‑Hermitian (algebra‑to‑graph):
Spectral graph is a general algebra-to-graph bridge. Because the equation \(\Phi(E) = - \log|a_q(E)| - \sum_{i=p+1}^{p+q}\log|\beta_i(E)|\) uses only \(P(E,z)\), thus
- Any bivariate Laurent polynomial \(P(z,E)\) has a spectralgraph.
- Any univariate polynomial \(P(z)\) can be viewed as one-band Bloch Hamiltonian; and any vector can be treated as a symmetrised coefficient list of a univariate polynomial.
- Any matrix can be decomposed into a product of one-band Hamiltonian matrices, which can form a multi-band Bloch Hamiltonian, so in general it has a multiset of spectral graphs.
You can get a universal topological fingerprint for many algebraic objects—making graph learning a front-door to problems in linear algebra, signal processing, photonics, circuits, and more.
5 A quick start: One‑band example
We’ll start from a simple one‑band model and utilizing Poly2Graph to obtain its spectral graph .
Characteristic polynomial
The model’s characteristic polynomial can be written as \(P(z,E) = z^4 - z^2 - z^{-1} - E\) (This corresponds to a scalar Bloch Hamiltonian \(h(z)=z^4-z^2-z^{-1}\), with \(z=e^{ik}\)).
Please ensure your version of Python >= 3.11 , you can check the installation:
print("Poly2Graph version:", p2g.__version__)Poly2Graph version: 0.2.0
# Always remember to define common symbols first
k = sp.symbols('k', real=True)
z, E = sp.symbols('z E', complex=True)The valid input formats to initialize a p2g.SpectralGraph object are:
Characteristic polynomial in terms of
zandE:- as a string of the Poly in terms of
zandE - as a
sympy’sPoly(sympy.polys.polytools.Poly) with {z,1/z,E} as generators
- as a string of the Poly in terms of
Bloch Hamiltonian in terms of
korz- as a
sympyMatrixin terms ofk - as a
sympyMatrixin terms ofz
- as a
All the following characteristics are valid and will initialize to the same characteristic polynomial and therefore produce the same spectral graph
char_poly_str = '-z**-1 - E - z**2 + z**4'
char_poly_Poly = sp.Poly(
-z**-1 - E - z**2 + z**4,
z, 1/z, E # generators are z, 1/z, E
)
phase_k = sp.exp(sp.I*k)
char_hamil_k = sp.Matrix([-phase_k**-1 - phase_k**2 + phase_k**4])
char_hamil_z = sp.Matrix([-z**-1 - E - z**2 + z**4])Here we use the string format as the initialization example.
sg = p2g.SpectralGraph(char_poly_str, k=k, z=z, E=E)# print the number of energy bands
print('Bands:', sg.num_bands)
# print the max hopping range (p,q)
print('Max hop (right):', sg.poly_p, 'Max hop (left):', sg.poly_q)
# print the [Ereal_min,Ereal_max,Eimag_min,Eimag_max] window
print('Spectral window:',
dict(zip(['Re(E)_min', 'Re(E)_max', 'Im(E)_min', 'Im(E)_max'],
map(float, sg.spectral_square))))Bands: 1
Max hop (right): 1 Max hop (left): 4
Spectral window: {'Re(E)_min': -2.3113904784272243, 'Re(E)_max': 1.6398687049402647, 'Im(E)_min': -1.9756295916837434, 'Im(E)_max': 1.9756295916837456}
We will see Poly2Graph automatically compute set of properties next:
sg.ChP\(\displaystyle \operatorname{Poly}{\left( z^{4} - z^{2} - \frac{1}{z} - E, z, \frac{1}{z}, E, domain=\mathbb{Z} \right)}\)
Bloch Hamiltonian:
- For one-band model(The exponent of \(E\) is 1), it is a unique, \(1 \times 1\) matrix (scalar).
sg.h_k\(\displaystyle \left[\begin{matrix}e^{4 i k} - e^{2 i k} - e^{- i k}\end{matrix}\right]\)
- or in \(z\) format(recall that \(z = e^{ik}\)).
sg.h_z\(\displaystyle \left[\begin{matrix}- \frac{- z^{5} + z^{3} + 1}{z}\end{matrix}\right]\)
Frobenius Companion Matrix of \(P(z, E)\):
- The Frobenius companion matrix is a special matrix whose eigenvalues are exactly the roots of the characteristic polynomial \(P(z, E)\) for fixed \(E\).
- In
Poly2Graph,sg.companion_Egives this matrix (with \(E\) as a parameter, \(z\) as variable). - Purpose:
- Efficiently computes all \(z\)-roots for any \(E\) using linear algebra (eigenvalues), instead of slow generic root-finding algorithms.
- These \(z\)-roots are essential for calculating the spectral graph, GBZ, spectral potential, and density of states.
sg.companion_E\(\displaystyle \left[\begin{matrix}0 & 0 & 0 & 0 & 1\\1 & 0 & 0 & 0 & E\\0 & 1 & 0 & 0 & 0\\0 & 0 & 1 & 0 & 1\\0 & 0 & 0 & 1 & 0\end{matrix}\right]\)
It is a key tool for automating and accelerating spectral graph extraction in Poly2Graph.
5.1 Spectral potential \(\Phi(E)\), density of states \(\rho(E)\), and skeleton
We compute \(\Phi(E)\) and \(\rho(E)\) on a grid of complex energies, then binarize \(\rho(E)\) to get the skeleton of the spectral graph. The phi and dos attributes store \(\Phi(E)\) and \(\rho(E)\) values on the grid, while skel is a boolean array indicating where \(\rho(E)\) has supported.
phi, dos, skel = sg.spectral_images()
fig, axes = plt.subplots(1, 3, figsize=(8, 3), sharex=True, sharey=True)
# 1) Spectral potential
axes[0].imshow(phi, extent=sg.spectral_square, origin='lower', cmap='terrain')
axes[0].set(xlabel='Re(E)', ylabel='Im(E)', title='Spectral Potential')
# 2) Density of States
pmin, pmax = np.percentile(dos, (0.1, 99.9))
# Clip extreme DOS to increase visibility
norm = colors.Normalize(vmin=pmin, vmax=pmax)
axes[1].imshow(dos, extent=sg.spectral_square, cmap='viridis', norm=norm)
axes[1].set(xlabel='Re(E)', title='Density of States')
# 3) Binarized skeleton
axes[2].imshow(skel, extent=sg.spectral_square, cmap='gray')
axes[2].set(xlabel='Re(E)', title='Graph Skeleton')
plt.tight_layout()
plt.savefig("assets/1-band-example_si.png")
plt.show()
6 What was hard before (and why we need Poly2Graph)?
Prior to Poly2Graph, extracting spectral graphs was manual and fragile:
- You had to manually plot long chain spectra, and visually infer the continum graph; for some scenarios of extremely complex spectra, they are plotted slolwly and fragile.
- Computing the GBZ roots \(\beta_i(E)\) for every sampled energy \(E\) is a bottleneck; naive solvers are slow and memory‑hungry.
- Even with a DOS image, turning that into a clean graph with correct endpoints, junctions, and loops requires careful morphology (thresholding, skeletonization, node/edge parsing).
Poly2Graph lifts these barriers with an automated end‑to‑end, high‑performance pipeline:
- Accepts either \(H(z)\) (as a
sympy.Matrix) or \(P(z,E)\) (string orsympy.Poly).
- Computes the spectral potential \(\Phi(E)\) from \(z\)‑roots (fast eigen‑solvers on Frobenius companion matrices; optional GPU/TPU acceleration via TensorFlow/PyTorch).
- Takes the Laplacian on Rokin function to get DOS, then does adaptive, two‑stage refinement (coarse mask → high‑res on just ~1–5% of the region).
- In rare low‑DOS or long‑range multi‑band settings, local numerical instabilities can arise, however,
Poly2Graphmitigates them with node‑merging and short‑edge contraction.
This automation has enabled HSG‑12M (11.6M static + 5.1M temporal Hamiltonian spectral multigraphs), demonstrating scale and diversity previously out of reach (Learn more from HSG-12M: A Large-Scale Spatial Multigraph Dataset if interested).
7 Mathematics and Physics
In this section, we summarize the key mathematical objects that appear in modern treatments of spectral graphs: the characteristic polynomial \(P(z,E)\), the spectral potential \(\Phi(E)\), and the density of states \(\rho(E)\).
Algebraic formulation:
Let \(H(z)\) be the Bloch Hamiltonian with \(z=e^{ik}\) and \[ P(z,E)=\det\!\big[H(z)-EI\big]=\sum_{n=-p}^{q} a_n(E)\,z^n . \] For a fixed \(E\), order the \(z\)‑roots of \(P(z,E)=0\) by magnitude \(|\beta_1(E)|\le\cdots\le|\beta_{p+q}(E)|\). The generalized Brillouin zone (GBZ) is characterized by the condition: \[ |\beta_p(E)|=|\beta_{p+1}(E)|, \]
and the corresponding loci of \(E\) form the OBC spectral graph. In particular, the density of states (DOS) in the thermodynamic limit (Number of cells \(N\to\infty\)) is supported only along these loci in the distributional sense.
Potential‑theoretic view:
A convenient “spectral potential” (Ronkin function) can be defined from the \(z\)‑roots; one can wirte as: \[ \Phi(E)=-\log|a_q(E)|-\sum_{i=p+1}^{p+q}\log|\beta_i(E)|. \] Where \(a_q(E)\) is the leading coefficient of the characteristic polynomial \(P(z,E)\). Its Laplacian yields the density of states(DOS), \[ \rho(E)=-\frac{1}{2\pi}\,\nabla^2\Phi(E), \] where the “\(-\)” sign depends on the convention used for \(\Phi\). In the distributional sense, \(\rho(E)\) is supported only on the loci of spectral graph. Equivalently, the spectral graph coincides with the ridges of \(\Phi(E)\).
Intuition: treat each eigenvalue \(\epsilon_n\) as a tiny electric charge \(\rho(E) = \lim_{N\to\infty}\sum_n \frac{1}{N} \delta(E-\epsilon_n)\); while \(\Phi(E)\) is an electrostatic‑like potential whose “ridges” trace the spectral graph; \(\rho(E)\) is nonzero only on the graph. Please see the Section 12 below for a concrete illustration.
8 Extract the spectral graph
Continue with the one-band model in the quick start part, we visualize these results by an interactive 3D surface plot of \(\Phi(E)\). Feel free to rotate/zoom the plot to examine the surface and skeleton from different angles.
import plotly.graph_objects as go
E_re = np.linspace(*sg.spectral_square[:2], phi.shape[0])
E_im = np.linspace(*sg.spectral_square[2:], phi.shape[1])
fig = go.Figure(data=[go.Surface(z=phi, x=E_re, y=E_im,
opacity=0.6, colorscale='Spectral_r')])
fig.update_layout(
scene=dict(
aspectratio=dict(x=1.5, y=1, z=.8),
xaxis_title='Re(E)',yaxis_title='Im(E)',zaxis_title='Phi(E)',
),
title='3D Surface Plot of Spectral Potential',
width=700, height=600
)
fig.show()